package com.etc.youkeshoppingssm.service.impl;

import com.etc.youkeshoppingssm.dao.IShoppingCartDao;
import com.etc.youkeshoppingssm.entity.ShoppingCart;
import com.etc.youkeshoppingssm.service.IShoppingCartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ShoppingCartServiceImpl implements IShoppingCartService {
    private final static Logger logger = LoggerFactory.getLogger(ShoppingCartServiceImpl.class);
    @Autowired
    private IShoppingCartDao dao;
    @Override
    public boolean addCart(ShoppingCart sc) {
        //根据上送的购物车相关数据,查询在该用户的该商品在购物车中是否存在,返回查询到的购物车相关数据
        ShoppingCart cart = dao.findOfCart(sc);
        int num = 0;
        logger.info("{}",cart);
        // 当查询回来的数据为空时,表示在购物车中不存在此数据
        if (cart == null) {
            num = dao.addCart(sc);
        }else{
        // 查询返回有数据的时候,表示在购物车存在此数据,将购物车中的数据进行修改,数量增加
            sc.setCartId(cart.getCartId());
            num = dao.modifyOfCart(sc);
        }
        logger.info("{}",sc.getCartId());
        if (num != 0){
            return true;
        }
        return false;
    }

    /**
     * 根据userId查询该用户的购物车信息
     *
     * @param userId
     * @return
     */
    @Override
    public int showNum(int userId) {
        int num = dao.showNum(userId);
        return num;
    }

    /**
     * 根据userId 查询购物车商品相关信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCart> findAllByUser(int userId) {
        List<ShoppingCart> list = dao.findAllByUser(userId);
        return list;
    }

    /**
     * 根据购物车ID修改商品的数量
     *
     * @param cartId
     * @param goodsCnt
     * @return
     */
    @Override
    public boolean updateCart(int cartId, int goodsCnt) {
        int num = dao.updateCart(cartId, goodsCnt);
        if (num != 0){
            return true;
        }
        return false;
    }

    /**
     * 根据购物车编号删除自己购物车的相关信息
     *
     * @param cartId
     * @return
     */
    @Override
    public boolean deleteCart(int cartId) {
        int num = dao.deleteCart(cartId);
        logger.info("根据上送的cartId,影响行数为{}",num);
        if (num != 0){
            return true;
        }
        return false;
    }
}
